using MediatR;
using RBAC.Domain.ProductionPlans;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.ProductionPlans;
using RBAC.Interstructrue.Base;
using System;

namespace RBAC.Read.Api.Application.Handler.ProductionPlans
{
    public class ByIdProductionPlanCommandHandler : IRequestHandler<ByIdProductionPlanCommands, APIResult<ProductionPlan>>
    {
        private readonly IBaseRepository<ProductionPlan> _planRepo;

        public ByIdProductionPlanCommandHandler(IBaseRepository<ProductionPlan> planRepo)
        {
            _planRepo = planRepo;
        }

        public Task<APIResult<ProductionPlan>> Handle(ByIdProductionPlanCommands request, CancellationToken cancellationToken)
        {
            try
            {
                if (request == null || request.ProductionPlanId <= 0)
                {
                    return Task.FromResult(new APIResult<ProductionPlan>
                    {
                        Code = APIEnums.Fail,
                        Msg = "参数错误：ProductionPlanId 无效",
                        Data = null
                    });
                }

                var model = _planRepo.GetModel(request.ProductionPlanId);

                if (model == null)
                {
                    return Task.FromResult(new APIResult<ProductionPlan>
                    {
                        Code = APIEnums.Fail,
                        Msg = "记录不存在或已删除",
                        Data = null
                    });
                }

                return Task.FromResult(new APIResult<ProductionPlan>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = model
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<ProductionPlan>
                {
                    Code = APIEnums.Fail,
                    Msg = "查询异常: " + ex.Message,
                    Data = null
                });
            }
        }
    }
}
